package com.danawa.mds.market.model;

import java.util.HashSet;
import java.util.Set;

public class Order {
	private Long id;
	private String orderId;
	private Buyer buyer;
	private Set<OrderLineItem> lineItems = new HashSet<OrderLineItem>();

	Order(String orderId, Buyer buyer) {
		this.orderId = orderId;
		this.buyer = buyer;
	}

	public Order with(String goodsId, int quantity)
			throws OrderLimitExceededException {
		return with(new OrderLineItem(goodsId, quantity));
	}

	private Order with(OrderLineItem lineItem) 
			throws OrderLimitExceededException {
		if (isExceedLimit(buyer, lineItem)) {
			throw new OrderLimitExceededException();
		}
		
		for (OrderLineItem eachItem : lineItems) {
			if (eachItem.isGoodsEqual(lineItem)) {
				eachItem.merge(lineItem);
				return this;
			}
		}
		
		lineItems.add(lineItem);
		return this;
	}
	
	private boolean isExceedLimit(Buyer buyer, OrderLineItem lineItem) {
		return buyer.isExceedLimitPrice(getPrice().add(lineItem.getPrice()));
	}
	
	public Money getPrice() {
		Money result = new Money(0);
		
		for (OrderLineItem eachItem : lineItems) {
			result = result.add(eachItem.getPrice());
		}
		
		return result;
	}

	public static Order order(String orderId, Buyer buyer) {
		return new Order(orderId, buyer);
	}

	public int getOrderLineItemSize() {
		return lineItems.size();
	}

	public boolean isOrderedBy(Buyer buyer) {
		return this.buyer == buyer;
	}

	public Long getId() {
		return id;
	}

	String getOrderId() {
		return orderId;
	}

	@Override
	public int hashCode() {
		return this.orderId.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		
		if (!(obj instanceof Order)) {
			return false;
		}
		
		final Order other = (Order) obj;
		return this.orderId.equals(other.getOrderId());
	}

}
